package com.hk.core.autoconfigure.data.r2dbc;

import com.hk.core.authentication.api.TenantInfo;
import com.hk.core.authentication.api.reactive.ReactiveSecurityContextUtils;
import com.hk.core.data.r2dbc.tenants.UserTenantAware;
import lombok.Setter;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author Kevin
 * @date 2024-04-20 23:30
 */
@Setter
public final class SpringSecurityUserTenantAware implements UserTenantAware {

    private String defaultTenantId = "default";

    @Override
    public Mono<String> getCurrentTenantId() {
        return ReactiveSecurityContextUtils.isAuthenticated()
                .flatMap(authenticated -> authenticated ? ReactiveSecurityContextUtils.getPrincipal()
                        .map(principal -> {
                            TenantInfo tenantInfo = principal.getTenantInfo();
                            return Objects.isNull(tenantInfo) || Objects.isNull(tenantInfo.getTenantId()) ? null : String.valueOf(tenantInfo.getTenantId());
                        }) : Mono.empty())
                .defaultIfEmpty(defaultTenantId);
    }
}
